﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using BluSteamServer.Model.Entities;

namespace BluSteamServer.Model
{
    public class EventListener
    {
        public void OnUserConnect(object sender, EventArgs e)
        {
            // get the list of connected users
            ConnectionManager cm = sender as ConnectionManager;
            List<string> users = new List<string>(cm.GetConnectionDictionary().Keys);

            this.UpdateClientsUserList(users);
        }

        public void OnUserDisconnect(object sender, EventArgs e)
        {
            // get the list of connected users
            ConnectionManager cm = sender as ConnectionManager;
            List<string> users = new List<string>(cm.GetConnectionDictionary().Keys);

            this.UpdateClientsUserList(users);
        }

        private void UpdateClientsUserList(List<string> users)
        {
            // serialize to xml
            ConnectedUserList userList = new ConnectedUserList() { Users = users };
            XmlSerializer serializer = new XmlSerializer(typeof(ConnectedUserList));

            StringBuilder userListXml = new StringBuilder();
            using (StringWriter writer = new StringWriter(userListXml))
            {
                serializer.Serialize(writer, userList);
            }

            // broadcast new ConnectedUserList object
            string message = "$CP2011~SERVER~RESPONSE~UPDATE_USERLIST~" + userListXml.ToString();
            Network.Broadcast(message);
        }
    }
}
